
#include <stdio.h>     // 标准输入输出库
#include <fcntl.h>     // 文件控制操作库，用于 open 等函数
#include <unistd.h>    // POSIX 标准符号接口，用于 sleep 等函数
#include <sys/ioctl.h> // 设备控制操作库，用于 ioctl 函数
#include <errno.h>     // 错误码定义，用于 perror 等函数
#include <stdlib.h>
#include <signal.h>
#include <time.h>



#define GEC6818_MOTOR_FORWARD	1//_IO('M', 0x01)    //电机
#define GEC6818_MOTOR_BACKWARD	2//_IO('M', 0x02)
#define GEC6818_MOTOR_STOP		3//_IO('M', 0x03)

static int djFd_;
static int cmd = 0;

void timer_handler(int sig, siginfo_t *si, void *uc)
{
    //printf("Timer tick\n");
    if(cmd == 1)
    {
        int ret = ioctl(djFd_,GEC6818_MOTOR_FORWARD,1);//3是速度  正传
        //printf("kai\n");
        if(ret < 0)
        {
                perror("dj error");
        }
    }
    else if(cmd == 1)
    {
            ioctl(djFd_,1,2);
    }
}

//0-停 1-正转 2-反转
void set_step(int c)
{
    cmd = c;
}

int init_step()
{
    djFd_ = open("/dev/stepmotor", O_RDWR);     //打开设备
    if(djFd_ < 0)
    {
        perror("open stepmotor driver");
    }

    struct sigaction sa;
    struct sigevent sev;
    struct itimerspec its;
    timer_t timerid;

    // 设置信号处理函数
    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = timer_handler;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGRTMIN, &sa, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    // 创建定时器
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;
    sev.sigev_value.sival_ptr = &timerid;
    if (timer_create(CLOCK_MONOTONIC, &sev, &timerid) == -1) {
        perror("timer_create");
        exit(EXIT_FAILURE);
    }

    // 设置定时器参数
    its.it_value.tv_sec = 0;
    its.it_value.tv_nsec = 10000000;
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 10000000;

    // 启动定时器
    if (timer_settime(timerid, 0, &its, NULL) == -1)
    {
        perror("timer_settime");
        exit(EXIT_FAILURE);
    }

    return 0;
}
